package com.qs.service;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.infomanage.authority.AuthorityBean;
import com.infomanage.bean.FieldBean;
import com.infomanage.bean.PaginationBean;
import com.infomanage.bean.SearchBean;
import com.infomanage.enums.RoleType;
import com.infomanage.exception.DaoException;
import com.infomanage.po.User;
import com.infomanage.util.Consts;
import com.infomanage.util.StringUtil;
import com.jiuqi.util.ReturnObject;
import com.jiuqi.util.StringUtils;
import com.qs.dao.QsStarCheckDAO;
import com.qs.po.QsStarCheck;
import com.qs.vo.QsStarCheckItem;
import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;

public class StarCheckService {

	public final static int CHECK_TYPE_HIGHER = 0;
	public final static int CHECK_TYPE_ZHONGDUI = 1;

	public static QsStarCheckItem load(HttpServletRequest request,
			HttpServletResponse response, JspWriter out) {
		try {
			request.setCharacterEncoding("UTF-8");
			String itemId = request.getParameter("itemId");
			QsStarCheckDAO dao = new QsStarCheckDAO();
			if (StringUtils.isEmpty(itemId))
				return null;
			QsStarCheckItem item = dao.find(Integer.parseInt(itemId));
			byte[] bytes = item.getBean().getData();
			loadData(item, bytes);
			return item;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private static Document initLoad(byte[] bytes) throws Exception {
		if (bytes == null || new String(bytes).equalsIgnoreCase("")) {
			return null;
		} else {
			InputStream in = new ByteArrayInputStream(bytes);
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			dbf.setValidating(false);
			dbf.setIgnoringComments(true);
			dbf.setIgnoringElementContentWhitespace(true);
			DocumentBuilder db = dbf.newDocumentBuilder();
			return db.parse(in);
		}
	}

	private static void loadData(QsStarCheckItem item, byte[] data) {
		try {
			Document doc = initLoad(data);
			Element root = doc.getDocumentElement();
			item.setCdzt(Integer.parseInt(getStrAttribute(root, "cdzt", "0")));
			item.setClby(Integer.parseInt(getStrAttribute(root, "clby", "0")));
			item.setDg(Integer.parseInt(getStrAttribute(root, "dg", "0")));
			item.setDq(Integer.parseInt(getStrAttribute(root, "dq", "0")));
			item.setFwc(Integer.parseInt(getStrAttribute(root, "fwc", "0")));
			item.setGgcc(Integer.parseInt(getStrAttribute(root, "ggcc", "0")));
			item.setHxq(Integer.parseInt(getStrAttribute(root, "hxq", "0")));
			item.setJdq(Integer.parseInt(getStrAttribute(root, "jdq", "0")));
			item.setJhyq(Integer.parseInt(getStrAttribute(root, "jhyq", "0")));
			item.setJlq(Integer.parseInt(getStrAttribute(root, "jlq", "0")));
			item.setJlxd(Integer.parseInt(getStrAttribute(root, "jlxd", "0")));
			item.setJz(Integer.parseInt(getStrAttribute(root, "jz", "0")));
			item.setKg(Integer.parseInt(getStrAttribute(root, "kg", "0")));
			item.setLpsd(Integer.parseInt(getStrAttribute(root, "lpsd", "0")));
			item.setLqm(Integer.parseInt(getStrAttribute(root, "lqm", "0")));
			item.setPcgj(Integer.parseInt(getStrAttribute(root, "pcgj", "0")));
			item.setPs(Integer.parseInt(getStrAttribute(root, "ps", "0")));
			item.setQtyq(Integer.parseInt(getStrAttribute(root, "qtyq", "0")));
			item.setSj(Integer.parseInt(getStrAttribute(root, "sj", "0")));
			item.setSpsd(Integer.parseInt(getStrAttribute(root, "spsd", "0")));
			item.setSsq(Integer.parseInt(getStrAttribute(root, "ssq", "0")));
			item.setTy(Integer.parseInt(getStrAttribute(root, "ty", "0")));
			item.setWjq(Integer.parseInt(getStrAttribute(root, "wjq", "0")));
			item.setWmpy(Integer.parseInt(getStrAttribute(root, "wmpy", "0")));
			item
					.setXfccz(Integer.parseInt(getStrAttribute(root, "xfccz",
							"0")));
			item.setXfqc(Integer.parseInt(getStrAttribute(root, "xfqc", "0")));
			item.setYdzz(Integer.parseInt(getStrAttribute(root, "ydzz", "0")));
			item.setYl(Integer.parseInt(getStrAttribute(root, "yl", "0")));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private static String getStrAttribute(Element e, String tagName,
			String defValue) {
		Node node = e.getAttributes().getNamedItem(tagName);
		if (node == null) {
			return defValue;
		} else {
			if (node.getNodeValue().equals(""))
				return defValue;
			return node.getNodeValue();
		}
	}

	public static List<QsStarCheckItem> loadList(HttpServletRequest request,
			HttpServletResponse response, JspWriter out) {
		try {
			request.setCharacterEncoding("UTF-8");
			QsStarCheckDAO dao = new QsStarCheckDAO();
			List<QsStarCheckItem> list = dao.findAll();
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static ReturnObject save(HttpServletRequest request,
			HttpServletResponse response, JspWriter out) {
		ReturnObject ret = new ReturnObject();
		try {
			request.setCharacterEncoding("UTF-8");
			QsStarCheck bean = new QsStarCheck();
			bean.setDeptId(Integer.parseInt(request.getParameter("deptId")));
			bean.setDate(request.getParameter("date"));
			bean.setKind(Integer.parseInt(request.getParameter("kind")));
			bean.setPersonName(request.getParameter("personName"));
			bean.setLevel(Integer.parseInt(request.getParameter("level")));
			byte[] bytes = saveToBytes(saveData(request));
			bean.setData(bytes);
			QsStarCheckDAO dao = new QsStarCheckDAO();
			dao.add(bean);
		} catch (Exception e) {
			ret.SetErrored(true);
			ret.setErrorMessage(e.getMessage());
		}
		return ret;
	}

	private static Map<String, String> saveData(HttpServletRequest request) {
		Map<String, String> mapper = new HashMap<String, String>();
		mapper.put("hxq", request.getParameter("hxq"));
		mapper.put("jdq", request.getParameter("jdq"));
		mapper.put("wjq", request.getParameter("wjq"));
		mapper.put("ssq", request.getParameter("ssq"));
		mapper.put("qtyq", request.getParameter("qtyq"));
		mapper.put("ydzz", request.getParameter("ydzz"));
		mapper.put("lpsd", request.getParameter("lpsd"));
		mapper.put("spsd", request.getParameter("spsd"));
		mapper.put("xfccz", request.getParameter("xfccz"));
		mapper.put("pcgj", request.getParameter("pcgj"));
		mapper.put("jlq", request.getParameter("jlq"));
		mapper.put("dg", request.getParameter("dg"));
		mapper.put("ps", request.getParameter("ps"));
		mapper.put("ty", request.getParameter("ty"));
		mapper.put("dq", request.getParameter("dq"));
		mapper.put("jz", request.getParameter("jz"));
		mapper.put("yl", request.getParameter("yl"));
		mapper.put("wmpy", request.getParameter("wmpy"));
		mapper.put("jlxd", request.getParameter("jlxd"));
		mapper.put("lqm", request.getParameter("lqm"));
		mapper.put("fwc", request.getParameter("fwc"));
		mapper.put("jhyq", request.getParameter("jhyq"));
		mapper.put("xfqc", request.getParameter("xfqc"));
		mapper.put("ggcc", request.getParameter("ggcc"));
		mapper.put("clby", request.getParameter("clby"));
		mapper.put("cdzt", request.getParameter("cdzt"));
		mapper.put("kg", request.getParameter("kg"));
		mapper.put("sj", request.getParameter("sj"));
		return mapper;

	}

	private static byte[] saveToBytes(Map<String, String> mapper)
			throws Exception {
		if (mapper == null || mapper.size() == 0) {
			return "".getBytes();
		} else {
			ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.newDocument();
			Element root = addElem(doc, doc, "data");
			for (Entry<String, String> entry : mapper.entrySet()) {
				setStringAttribute(root, entry.getKey(), entry.getValue());
			}
			OutputFormat of = new OutputFormat(doc, "UTF-8", false);
			of.setLineSeparator("\n");
			XMLSerializer xs = new XMLSerializer(out, of);
			xs.serialize(doc);
			return out.toByteArray();
		}
	}

	private static Element addElem(Document doc, Node parent, String name) {
		Element elem = doc.createElement(name);
		parent.appendChild(elem);
		return elem;
	}

	private static void setStringAttribute(Element ele, String name,
			String value) {
		ele.setAttribute(name, value == null ? "" : value);
	}

	public static ReturnObject remove(HttpServletRequest request,
			HttpServletResponse response, JspWriter out) {
		ReturnObject ret = new ReturnObject();
		try {
			request.setCharacterEncoding("UTF-8");
			String studyId = request.getParameter("itemId");
			QsStarCheckDAO dao = new QsStarCheckDAO();
			dao.remove(QsStarCheck.class, Integer.parseInt(studyId));
		} catch (Exception e) {
			ret.SetErrored(true);
			ret.setErrorMessage(e.getMessage());
		}
		return ret;
	}

	public static ReturnObject removeBatch(HttpServletRequest request,
			HttpServletResponse response, JspWriter out) {
		ReturnObject ret = new ReturnObject();
		try {
			request.setCharacterEncoding("UTF-8");
			String batchIds = request.getParameter("batchIds");
			QsStarCheckDAO dao = new QsStarCheckDAO();
			if (batchIds != null) {
				String[] ids = batchIds.split(";");
				for (String id : ids) {
					dao.remove(QsStarCheck.class, Integer.parseInt(id));
				}
			}
		} catch (Exception e) {
			ret.SetErrored(true);
			ret.setErrorMessage(e.getMessage());
		}
		return ret;
	}

	public static ReturnObject modify(HttpServletRequest request,
			HttpServletResponse response, JspWriter out) {
		ReturnObject ret = new ReturnObject();
		try {
			request.setCharacterEncoding("UTF-8");
			int itemId = Integer.parseInt(request.getParameter("itemId"));
			QsStarCheckDAO dao = new QsStarCheckDAO();
			QsStarCheck bean = dao.find(QsStarCheck.class, itemId);
			bean.setDeptId(Integer.parseInt(request.getParameter("deptId")));
			bean.setDate(request.getParameter("date"));
			bean.setKind(Integer.parseInt(request.getParameter("kind")));
			bean.setPersonName(request.getParameter("personName"));
			bean.setLevel(Integer.parseInt(request.getParameter("level")));
			bean.setData(saveToBytes(saveData(request)));
			dao.modify(bean);
		} catch (Exception e) {
			ret.SetErrored(true);
			ret.setErrorMessage(StringUtil.filterIllegalchar(e.getMessage()));
		}
		return ret;
	}

	public static List<QsStarCheckItem> search(HttpServletRequest request,
			HttpServletResponse response, JspWriter out) {
		try {
			request.setCharacterEncoding("UTF-8");
			QsStarCheckDAO dao = new QsStarCheckDAO();
			SearchBean searchBean = buildSearchCondition(request, response, out);
			// 设置分页
			String currPageNum = request.getParameter("currPageNum");
			PaginationBean page = new PaginationBean();
			if (currPageNum == null) {
				page.setCurrentPageNum(1);
			} else {
				page.setCurrentPageNum(Integer.parseInt(currPageNum));

			}
			searchBean.setPage(page);
			List<QsStarCheckItem> list = dao.findByFields(searchBean);
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static int getPageCount(HttpServletRequest request,
			HttpServletResponse response, JspWriter out) {
		try {
			QsStarCheckDAO dao = new QsStarCheckDAO();
			SearchBean searchBean = buildSearchCondition(request, response, out);
			return (dao.count(searchBean) + PaginationBean.pageSize - 1)
					/ PaginationBean.pageSize;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 1;
	}

	private static SearchBean buildSearchCondition(HttpServletRequest request,
			HttpServletResponse response, JspWriter out) throws Exception {
		request.setCharacterEncoding("UTF-8");
		String deptId = request.getParameter("deptId");
		SearchBean searchBean = new SearchBean();
		if (!StringUtil.isEmpty(deptId)) {
			FieldBean field = new FieldBean("deptId", deptId);
			searchBean.add(field);
		}

		// 设置权限
		User user = (User) request.getSession().getAttribute(
				Consts.LOGINED_USER);
		if (user != null) {
			AuthorityBean authority = new AuthorityBean();
			authority.setRole(RoleType.valueOf(user.getRoleId()));
			authority.setDeptId(user.getAssociatedDept());
			searchBean.setAuthority(authority);
		}
		return searchBean;
	}

	public static List<QsStarCheckItem> generateReportData(
			HttpServletRequest request, HttpServletResponse response,
			JspWriter out) {
		try {
			request.setCharacterEncoding("UTF-8");

			String deptId = request.getParameter("deptId");
			String date = request.getParameter("date");
			SearchBean searchBean = new SearchBean();
			if (!StringUtil.isEmpty(deptId)) {
				FieldBean field = new FieldBean("deptId", deptId);
				searchBean.add(field);
			}
			if (!StringUtil.isEmpty(date)) {
				FieldBean field = new FieldBean("date", date);
				searchBean.add(field);
			}

			QsStarCheckDAO dao = new QsStarCheckDAO();
			List<QsStarCheckItem> list = dao.findByFields(searchBean);
			if(list != null) {
				for (QsStarCheckItem item : list) {
					loadData(item, item.getBean().getData());
				}
			}
			return list;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (DaoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;

	}
}
